<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import {
  submitPositionApi,
  getJobDetailApi,
  closeJobApi,
  openJobApi,
} from "@/api/position";

// 编辑模式相关状态
const isEditMode = ref(false); // 是否为编辑模式
const currentJobId = ref(""); // 当前编辑的职位ID
const isViolated = ref(false); // 是否为违规删除的职位
const violateReason = ref(""); // 违规删除原因
const jobStatus = ref(null); // 职位状态（1=开启，2=关闭，3=违规删除）

// 表单数据
const formData = ref({
  jobName: "",
  jobType: "", // 职位类别
  jobTypeId: "", // 职位类别ID
  expYears: "",
  edu: "",
  beginSalary: 0,
  endSalary: 0,
  monthlySalary: 0,
  jobDesc: "", // 职位描述（纯文本）
  jobDescHtml: "", // 职位描述（富文本HTML）
  tags: "",
  city: "",
  address: "",
  jobTags: [], // 职位标签数组
});

// 经验要求选项
const experienceRange = ref([
  "不限",
  "1年以下",
  "1-3年",
  "3-5年",
  "5-10年",
  "10年以上",
]);
const selectedExperienceIndex = ref(0);

// 学历要求选项
const educationRange = ref([
  "不限",
  "中专/技校",
  "大专",
  "本科",
  "硕士",
  "MBA/EMBA",
  "博士",
]);
const selectedEducationIndex = ref(0);

// 薪资选项
const salaryRange = ref([[], [], []]);
const selectedSalaryIndex = ref([0, 0, 0]);

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 跳转到职位名称输入页面
const goToJobNameInput = () => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  uni.navigateTo({
    url: `/pages/candidate/resume/commonInput?type=jobName&value=${encodeURIComponent(
      formData.value.jobName || ""
    )}`,
  });
};

// 跳转到职位类别选择页面
const goToJobTypeSelector = () => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  // 传递当前选中的职位类别信息
  const currentJobType = {
    jobType: formData.value.jobType,
    jobTypeId: formData.value.jobTypeId,
  };
  uni.setStorageSync("currentJobType", currentJobType);

  uni.navigateTo({
    url: "/pages/common/jobTypeSelector",
  });
};

// 跳转到工作地点输入页面
const goToAddressInput = () => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  uni.navigateTo({
    url: `/pages/candidate/resume/commonInput?type=address&value=${encodeURIComponent(
      formData.value.address || ""
    )}`,
  });
};

// 跳转到职位描述编辑页面
const goToJobDescEdit = () => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  uni.navigateTo({
    url: `/pages/candidate/resume/richTextEditor?type=jobDesc&value=${encodeURIComponent(
      formData.value.jobDescHtml || ""
    )}`,
  });
};

// 跳转到城市选择页面
const goToCitySelector = () => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  // 传递当前选中的城市
  uni.setStorageSync("currentCity", formData.value.city);

  uni.navigateTo({
    url: "/pages/company/citySelector",
  });
};

// 跳转到职位标签页面
const goToPositionTags = () => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  // 将当前标签存储到本地，供标签页面使用
  uni.setStorageSync("currentTags", formData.value.jobTags);

  // 通过URL参数传递当前标签
  const currentTagsString = formData.value.jobTags.join(",");

  uni.navigateTo({
    url: `/pages/company/position/positionTags?value=${encodeURIComponent(
      currentTagsString
    )}`,
  });
};

// 经验要求选择变化
const onExperienceChange = (e) => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  selectedExperienceIndex.value = e.detail.value;
  formData.value.expYears = experienceRange.value[e.detail.value];
};

// 学历要求选择变化
const onEducationChange = (e) => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  selectedEducationIndex.value = e.detail.value;
  formData.value.edu = educationRange.value[e.detail.value];
};

// 薪资选择变化
const onSalaryChange = (e) => {
  // 违规删除的职位不允许编辑
  if (isViolated.value) {
    return;
  }
  selectedSalaryIndex.value = e.detail.value;
  const startSalary = salaryRange.value[0][e.detail.value[0]];
  const endSalary = salaryRange.value[1][e.detail.value[1]];
  const monthSalary = salaryRange.value[2][e.detail.value[2]];

  if (startSalary && endSalary && monthSalary) {
    formData.value.beginSalary = parseInt(startSalary.replace("K", ""));
    formData.value.endSalary = parseInt(endSalary.replace("K", ""));
    formData.value.monthlySalary = parseInt(monthSalary.replace("个月", ""));
  }
};

// 获取薪资显示文本
const getSalaryDisplay = () => {
  if (
    formData.value.beginSalary &&
    formData.value.endSalary &&
    formData.value.monthlySalary
  ) {
    return `${formData.value.beginSalary}-${formData.value.endSalary}K·${formData.value.monthlySalary}个月`;
  }
  return "请选择";
};

// 获取标签显示文本
const getTagsDisplay = () => {
  if (formData.value.jobTags && formData.value.jobTags.length > 0) {
    return formData.value.jobTags.join(",");
  }
  return "请选择职位标签";
};

// 获取职位描述显示文本（移除HTML标签）
const getJobDescDisplay = () => {
  if (!formData.value.jobDesc) return "请填写职位描述";

  // 已经是纯文本，但为了安全起见，再次移除HTML标签
  const plainText = formData.value.jobDesc.replace(/<[^>]*>/g, "");

  // 如果超过100字，截取前100字并添加省略号
  if (plainText.length > 100) {
    return plainText.substring(0, 100) + "...";
  }

  return plainText || "请填写职位描述";
};

// 将标签数组转换为字符串（提交时使用）
const convertTagsToString = () => {
  if (formData.value.jobTags && formData.value.jobTags.length > 0) {
    formData.value.tags = formData.value.jobTags.join(",");
  } else {
    formData.value.tags = "";
  }
};

// 将标签字符串转换为数组（编辑时使用）
const convertTagsToArray = () => {
  if (formData.value.tags) {
    formData.value.jobTags = formData.value.tags
      .split(",")
      .filter((tag) => tag.trim());
  } else {
    formData.value.jobTags = [];
  }
};

// 获取职位详情
const getJobDetail = async (jobId) => {
  try {
    console.log("获取职位详情 - jobId:", jobId);
    const response = await getJobDetailApi(jobId);
    console.log("职位详情响应:", response);

    if (response) {
      // 记录职位状态
      jobStatus.value = response.status;

      // 检查是否为违规删除的职位（status: 3 代表违规删除）
      isViolated.value = response.status === 3;
      if (isViolated.value) {
        violateReason.value = response.violateReason || "违规原因未知";
        console.log("违规删除的职位，原因:", violateReason.value);
      }

      // 填充表单数据
      formData.value = {
        ...formData.value,
        id: response.id,
        jobName: response.jobName || "",
        jobType: response.jobType || "",
        expYears: response.expYears || "",
        edu: response.edu || "",
        beginSalary: response.beginSalary || 0,
        endSalary: response.endSalary || 0,
        monthlySalary: response.monthlySalary || 0,
        jobDesc: response.jobDesc || "",
        jobDescHtml: response.jobDescHtml || "",
        tags: response.tags || "",
        city: response.city || "",
        address: response.address || "",
      };

      // 转换标签格式
      convertTagsToArray();

      // 设置经验和学历选中索引
      updateSelectedIndexes();

      // 设置薪资选中索引
      updateSalaryIndexes();

      console.log("职位详情加载完成:", formData.value);
    }
  } catch (error) {
    console.error("获取职位详情失败:", error);
    uni.showToast({
      title: "获取职位详情失败",
      icon: "none",
    });
  }
};

// 更新经验和学历选中索引
const updateSelectedIndexes = () => {
  // 找到经验要求对应的索引
  const expIndex = experienceRange.value.findIndex(
    (item) => item === formData.value.expYears
  );
  if (expIndex !== -1) {
    selectedExperienceIndex.value = expIndex;
  }

  // 找到学历要求对应的索引
  const eduIndex = educationRange.value.findIndex(
    (item) => item === formData.value.edu
  );
  if (eduIndex !== -1) {
    selectedEducationIndex.value = eduIndex;
  }
};

// 更新薪资选中索引
const updateSalaryIndexes = () => {
  if (
    formData.value.beginSalary &&
    formData.value.endSalary &&
    formData.value.monthlySalary
  ) {
    // 找到对应的薪资索引
    const startIndex =
      salaryRange.value[0]?.findIndex(
        (item) => parseInt(item.replace("K", "")) === formData.value.beginSalary
      ) || 0;

    const endIndex =
      salaryRange.value[1]?.findIndex(
        (item) => parseInt(item.replace("K", "")) === formData.value.endSalary
      ) || 0;

    const monthIndex =
      salaryRange.value[2]?.findIndex(
        (item) =>
          parseInt(item.replace("个月", "")) === formData.value.monthlySalary
      ) || 0;

    selectedSalaryIndex.value = [startIndex, endIndex, monthIndex];
  }
};

// 初始化薪资选项
const initSalaryRange = () => {
  // 起始薪资
  const startSalaryArr = [];
  for (let i = 1; i <= 200; i++) {
    if (i <= 30) {
      startSalaryArr.push(i + "K");
    } else if (i <= 100 && i % 5 === 0) {
      startSalaryArr.push(i + "K");
    } else if (i > 100 && i % 10 === 0) {
      startSalaryArr.push(i + "K");
    }
  }

  // 结束薪资
  const endSalaryArr = [];
  for (let i = 2; i <= 200; i++) {
    if (i <= 30) {
      endSalaryArr.push(i + "K");
    } else if (i <= 100 && i % 5 === 0) {
      endSalaryArr.push(i + "K");
    } else if (i > 100 && i % 10 === 0) {
      endSalaryArr.push(i + "K");
    }
  }

  // 月薪个数
  const monthSalaryArr = [];
  for (let i = 12; i <= 30; i++) {
    monthSalaryArr.push(i + "个月");
  }

  salaryRange.value = [startSalaryArr, endSalaryArr, monthSalaryArr];
};

// 更新字段值（接收子页面传回的数据）
const updateFieldValue = (field, value) => {
  console.log("更新字段值:", field, value);
  if (formData.value.hasOwnProperty(field)) {
    formData.value[field] = value;

    // 如果是jobDesc或jobDescHtml，需要同步处理
    if (field === "jobDesc" || field === "jobDescHtml") {
      // 如果更新的是jobDescHtml，需要提取纯文本到jobDesc
      if (field === "jobDescHtml") {
        formData.value.jobDescHtml = value;
        formData.value.jobDesc = value.replace(/<[^>]*>/g, ""); // 移除HTML标签
      }
      // 如果更新的是jobDesc，直接赋值（此情况下假设已经是纯文本）
      else if (field === "jobDesc") {
        formData.value.jobDesc = value;
        // 如果没有jobDescHtml，也设置为相同值
        if (!formData.value.jobDescHtml) {
          formData.value.jobDescHtml = value;
        }
      }
    }
  }
};

// 关闭职位
const closeJob = async () => {
  try {
    uni.showModal({
      title: "提示",
      content: "确定要关闭这个职位吗？",
      success: async (res) => {
        if (res.confirm) {
          uni.showLoading({
            title: "关闭中...",
          });

          const response = await closeJobApi(currentJobId.value);

          uni.hideLoading();

          uni.showToast({
            title: "职位已关闭",
            duration: 2000,
            success() {
              setTimeout(() => {
                // 回到上一个页面并刷新数据
                uni.$emit("refreshJobList");
                uni.navigateBack();
              }, 2000);
            },
          });
        }
      },
    });
  } catch (error) {
    uni.hideLoading();
    console.error("关闭职位失败:", error);
    uni.showToast({
      title: error.message || "关闭失败，请稍后重试",
      icon: "none",
      duration: 3000,
    });
  }
};

// 开启职位
const openJob = async () => {
  try {
    uni.showModal({
      title: "提示",
      content: "确定要开启这个职位吗？",
      success: async (res) => {
        if (res.confirm) {
          uni.showLoading({
            title: "开启中...",
          });

          const response = await openJobApi(currentJobId.value);

          uni.hideLoading();

          uni.showToast({
            title: "职位已开启",
            duration: 2000,
            success() {
              setTimeout(() => {
                // 回到上一个页面并刷新数据
                uni.$emit("refreshJobList");
                uni.navigateBack();
              }, 2000);
            },
          });
        }
      },
    });
  } catch (error) {
    uni.hideLoading();
    console.error("开启职位失败:", error);
    uni.showToast({
      title: error.message || "开启失败，请稍后重试",
      icon: "none",
      duration: 3000,
    });
  }
};

// 发布职位
const submitJob = async () => {
  // 检查是否为违规删除的职位，如果是则不允许修改
  if (isViolated.value) {
    uni.showToast({
      title: "违规删除的职位不允许修改",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  // 转换标签格式（确保后端字段正确）
  convertTagsToString();

  // 表单验证
  if (!formData.value.jobName) {
    uni.showToast({
      title: "请输入职位名称",
      icon: "none",
    });
    return;
  }

  if (!formData.value.jobType) {
    uni.showToast({
      title: "请选择职位类别",
      icon: "none",
    });
    return;
  }

  if (!formData.value.expYears) {
    uni.showToast({
      title: "请选择经验要求",
      icon: "none",
    });
    return;
  }

  if (!formData.value.edu) {
    uni.showToast({
      title: "请选择学历要求",
      icon: "none",
    });
    return;
  }

  if (
    !formData.value.beginSalary ||
    !formData.value.endSalary ||
    !formData.value.monthlySalary
  ) {
    uni.showToast({
      title: "请选择薪资范围",
      icon: "none",
    });
    return;
  }

  if (formData.value.beginSalary >= formData.value.endSalary) {
    uni.showToast({
      title: "请选择合适的薪资范围",
      icon: "none",
    });
    return;
  }

  if (!formData.value.jobDesc) {
    uni.showToast({
      title: "请填写职位描述",
      icon: "none",
    });
    return;
  }

  if (!formData.value.tags) {
    uni.showToast({
      title: "请选择职位标签",
      icon: "none",
    });
    return;
  }

  if (!formData.value.city) {
    uni.showToast({
      title: "请选择工作城市",
      icon: "none",
    });
    return;
  }

  if (!formData.value.address) {
    uni.showToast({
      title: "请填写工作地点",
      icon: "none",
    });
    return;
  }

  try {
    // 显示加载状态
    uni.showLoading({
      title: "发布中...",
    });

    console.log("提交职位数据:", formData.value);

    // 调用API提交数据
    const response = await submitPositionApi(formData.value);

    uni.hideLoading();

    console.log("职位发布成功:", response);

    uni.showToast({
      title: "发布成功",
      duration: 2000,
      success() {
        setTimeout(() => {
          // 回到上一个页面并刷新数据
          uni.$emit("refreshJobList");
          uni.navigateBack();
        }, 2000);
      },
    });
  } catch (error) {
    uni.hideLoading();
    console.error("职位发布失败:", error);

    uni.showToast({
      title: error.message || "发布失败，请稍后重试",
      icon: "none",
      duration: 3000,
    });
  }
};

// 页面显示时处理返回数据
const handleOnShow = () => {
  console.log("页面显示，处理返回数据");
  // 获取选择的城市
  const selectedCity = uni.getStorageSync("selectedCity");
  console.log("正在检查selectedCity:", selectedCity);
  if (selectedCity) {
    console.log("获取到选择的城市:", selectedCity);
    formData.value.city = selectedCity;
    uni.removeStorageSync("selectedCity");
  }

  // 获取选择的职位类别
  const selectedJobType = uni.getStorageSync("selectedJobType");
  console.log("正在检查selectedJobType:", selectedJobType);
  if (selectedJobType) {
    console.log("获取到选择的职位类别:", selectedJobType);
    // 只使用第三级类别名称
    formData.value.jobType = selectedJobType.name || selectedJobType.fullPath;
    formData.value.jobTypeId = selectedJobType.id;
    uni.removeStorageSync("selectedJobType");
  }

  // 获取选择的职位标签
  const selectedTags = uni.getStorageSync("selectedTags");
  console.log("正在检查selectedTags:", selectedTags);
  if (selectedTags && Array.isArray(selectedTags)) {
    console.log("获取到选择的职位标签:", selectedTags);
    formData.value.jobTags = [...selectedTags];
    // 同步更新tags字段
    convertTagsToString();
    uni.removeStorageSync("selectedTags");
  }

  // 处理其他页面返回的数据（通用处理）
  const returnData = uni.getStorageSync("pageReturnData");
  if (returnData) {
    console.log("获取到通用返回数据:", returnData);
    const { field, value } = returnData;
    if (field && value !== undefined && formData.value.hasOwnProperty(field)) {
      formData.value[field] = value;

      // 如果是标签字段，需要同步转换
      if (field === "tags") {
        convertTagsToArray();
      }
    }
    uni.removeStorageSync("pageReturnData");
  }
};

// 页面加载
onMounted(() => {
  // 获取页面参数，检查是否为编辑模式
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};

  if (options.jobId) {
    console.log("编辑模式 - jobId:", options.jobId);
    isEditMode.value = true;
    currentJobId.value = options.jobId;
  } else {
    console.log("新增模式");
    isEditMode.value = false;
  }

  initSalaryRange();

  // 如果是编辑模式，先获取职位详情
  if (isEditMode.value) {
    getJobDetail(currentJobId.value);
  } else {
    // 新增模式设置默认值
    formData.value.expYears = experienceRange.value[0];
    formData.value.edu = educationRange.value[0];
  }

  // 初始化标签数据（如果是编辑模式）
  if (formData.value.tags) {
    convertTagsToArray();
  }

  // 监听职位名称更新事件
  uni.$on("updateJobName", (value) => {
    formData.value.jobName = value;
  });

  // 监听工作地点更新事件
  uni.$on("updateAddress", (value) => {
    console.log("工作地点更新:", value);
    formData.value.address = value;
  });

  // 监听富文本内容更新事件
  uni.$on("updateRichText", (data) => {
    console.log("富文本内容更新:", data);
    if (data.type === "jobDesc") {
      // 富文本编辑器返回的是HTML内容
      formData.value.jobDescHtml = data.contentHtml;
      // 提取纯文本到jobDesc字段
      formData.value.jobDesc = data.content
    }
  });

  // 监听城市选择事件
  uni.$on("citySelected", (city) => {
    console.log("城市选择更新:", city);
    formData.value.city = city.city
  });

  // 监听职位标签更新事件
  uni.$on("updateJobTags", (tags) => {
    console.log("职位标签更新:", tags);
    formData.value.jobTags = Array.isArray(tags) ? tags : [];
    // 同步更新tags字段
    convertTagsToString();
  });

  // 监听职位类别更新事件
  uni.$on("updateJobType", (value) => {
    console.log("职位类别更新:", value);
    // 只使用第三级类别名称
    formData.value.jobType = value.name || value;
    if (value.id) {
      formData.value.jobTypeId = value.id;
    }
  });

  // 调用 handleOnShow 方法以确保数据正确初始化
  handleOnShow();
});

// uni-app页面生命周期 - 页面显示时触发
function onShow() {
  console.log("addPosition页面onShow触发");
  handleOnShow();
}

// 页面卸载时移除事件监听器
onUnmounted(() => {
  uni.$off("updateJobName");
  uni.$off("updateAddress");
  uni.$off("updateRichText");
  uni.$off("citySelected");
  uni.$off("updateJobTags");
  uni.$off("updateJobType");
});

// 暴露生命周期函数和方法
defineExpose({
  onShow: handleOnShow,
  updateFieldValue,
});
</script>

<template>
  <view class="add-position-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <view class="header-right"></view>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <view class="card-box">
        <!-- 标题 -->
        <view class="title-wrapper">
          <text class="title-one">{{
            isEditMode ? "编辑职位" : "发布职位"
          }}</text>
        </view>

        <!-- 职位名称 -->
        <view class="block-name">
          <text class="field-lable-words">职位名称</text>
          <view
            class="field-wrapper"
            :class="{ 'field-disabled': isViolated }"
            @click="goToJobNameInput"
          >
            <text
              class="company-input"
              :class="{ placeholder: !formData.jobName }"
            >
              {{ formData.jobName || "请填入职位名称" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
              :class="{ 'arrow-disabled': isViolated }"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 职位类别 -->
        <view class="block-name">
          <text class="field-lable-words">职位类别</text>
          <view
            class="field-wrapper"
            :class="{ 'field-disabled': isViolated }"
            @click="goToJobTypeSelector"
          >
            <text
              class="company-input"
              :class="{ placeholder: !formData.jobType }"
            >
              {{ formData.jobType || "请选择职位类别" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
              :class="{ 'arrow-disabled': isViolated }"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 职位标签 -->
        <view class="block-name">
          <text class="field-lable-words">职位标签</text>
          <view
            class="field-wrapper"
            :class="{ 'field-disabled': isViolated }"
            @click="goToPositionTags"
          >
            <text
              class="company-input"
              :class="{
                placeholder: !formData.jobTags || formData.jobTags.length === 0,
              }"
            >
              {{ getTagsDisplay() }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
              :class="{ 'arrow-disabled': isViolated }"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 经验要求、学历要求、薪资范围 -->
        <view class="three-blocks">
          <view class="small-part">
            <text class="field-item-title">经验要求</text>
            <picker
              mode="selector"
              :range="experienceRange"
              :value="selectedExperienceIndex"
              @change="onExperienceChange"
              class="picker-words"
              :disabled="isViolated"
            >
              <view
                class="field-item-words"
                :class="{ 'picker-disabled': isViolated }"
                >{{ formData.expYears || "请选择" }}</view
              >
            </picker>
          </view>

          <view class="split">|</view>

          <view class="small-part">
            <text class="field-item-title">最低学历</text>
            <picker
              mode="selector"
              :range="educationRange"
              :value="selectedEducationIndex"
              @change="onEducationChange"
              class="picker-words"
              :disabled="isViolated"
            >
              <view
                class="field-item-words"
                :class="{ 'picker-disabled': isViolated }"
                >{{ formData.edu || "请选择" }}</view
              >
            </picker>
          </view>

          <view class="split">|</view>

          <view class="small-part">
            <text class="field-item-title">薪资范围</text>
            <picker
              mode="multiSelector"
              :range="salaryRange"
              :value="selectedSalaryIndex"
              @change="onSalaryChange"
              :class="
                getSalaryDisplay() === '请选择' ? 'picker' : 'picker-words'
              "
              :disabled="isViolated"
            >
              <view
                class="field-item-words"
                :class="{ 'picker-disabled': isViolated }"
                >{{ getSalaryDisplay() }}</view
              >
            </picker>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 职位描述 -->
        <view class="block-name">
          <text class="field-lable-words">职位描述</text>
          <view
            class="field-wrapper"
            :class="{ 'field-disabled': isViolated }"
            @click="goToJobDescEdit"
          >
            <text
              class="company-input"
              :class="{ placeholder: !formData.jobDesc }"
            >
              {{ getJobDescDisplay() }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
              :class="{ 'arrow-disabled': isViolated }"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 工作城市 -->
        <view class="block-name">
          <text class="field-lable-words">工作城市</text>
          <view
            class="field-wrapper"
            :class="{ 'field-disabled': isViolated }"
            @click="goToCitySelector"
          >
            <text
              class="company-input"
              :class="{ placeholder: !formData.city }"
            >
              {{ formData.city || "请选择工作城市" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
              :class="{ 'arrow-disabled': isViolated }"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 工作地点 -->
        <view class="block-name">
          <text class="field-lable-words">工作地点</text>
          <view
            class="field-wrapper"
            :class="{ 'field-disabled': isViolated }"
            @click="goToAddressInput"
          >
            <text
              class="company-input"
              :class="{ placeholder: !formData.address }"
            >
              {{ formData.address || "请填写真实工作地点(具体到园区门牌号)" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
              :class="{ 'arrow-disabled': isViolated }"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 违规删除提示 -->
        <view v-if="isViolated" class="violation-notice">
          <view class="violation-header">
            <image
              src="/static/icons/msg-warning.png"
              class="warning-icon"
            ></image>
            <text class="violation-title">违规删除提示</text>
          </view>
          <text class="violation-reason">违规原因：{{ violateReason }}</text>
          <text class="violation-desc"
            >该职位已被标记为违规删除，无法进行修改。如有疑问，请联系客服。</text
          >
        </view>

        <!-- 发布按钮 -->
        <view v-if="!isViolated" class="button-wrapper">
          <!-- 编辑模式下的关闭/开启按钮 -->
          <view
            v-if="isEditMode && jobStatus === 1"
            class="btn-action-wrapper"
            @click="closeJob"
          >
            <text class="btn-action-words">关闭职位</text>
          </view>
          <view
            v-if="isEditMode && jobStatus === 2"
            class="btn-action-wrapper"
            @click="openJob"
          >
            <text class="btn-action-words">开启职位</text>
          </view>

          <!-- 保存/发布按钮 -->
          <view class="btn-next-wrapper" @click="submitJob">
            <text class="btn-next-words">{{
              isEditMode ? "保存修改" : "发布职位"
            }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="less">
.add-position-container {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 140rpx; /* 为固定按钮留出空间 */
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  padding-top: calc(20rpx + var(--status-bar-height, 0));
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-right {
  width: 60rpx;
}

/* 表单内容样式 */
.form-content {
  flex: 1;
  background-color: #ffffff;
}

.card-box {
  padding: 20rpx 40rpx;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.title-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  margin-bottom: 60rpx;
}

.title-one {
  font-size: 48rpx;
  font-weight: 600;
  color: #333333;
}

.block-name {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-bottom: 40rpx;
}

.field-lable-words {
  font-size: 32rpx;
  color: #333333;
  margin-bottom: 20rpx;
}

.field-wrapper {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.company-input {
  font-size: 36rpx;
  color: #333333;
  flex: 1;
}

.placeholder {
  color: #b5bdbd;
}

.right-arrow {
  width: 36rpx;
  height: 36rpx;
}

/* 禁用状态样式 */
.field-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.arrow-disabled {
  opacity: 0.3;
}

.picker-disabled {
  opacity: 0.6;
  color: #999999 !important;
}

.line-wrapper {
  margin: 40rpx 0;
}

.line {
  width: 100%;
  height: 1rpx;
  background-color: #f0f0f0;
}

/* 三列布局 */
.three-blocks {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  margin: 40rpx 0;
}

.small-part {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.field-item-title {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 20rpx;
}

.field-item-words {
  font-size: 32rpx;
  color: #333333;
  text-align: center;
}

.split {
  font-size: 56rpx;
  color: #d4dcdf;
  font-weight: 200;
  margin: 0 20rpx;
}

.picker {
  color: #b5bdbd;
}

.picker-words {
  color: #333333;
}

/* 违规删除提示样式 */
.violation-notice {
  background-color: #fff2f0;
  border: 1rpx solid #ffccc7;
  border-radius: 8rpx;
  padding: 24rpx;
  margin: 40rpx 0;
}

.violation-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.warning-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
}

.violation-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #cf1322;
}

.violation-reason {
  font-size: 28rpx;
  color: #cf1322;
  line-height: 1.5;
  margin-bottom: 12rpx;
  display: block;
}

.violation-desc {
  font-size: 24rpx;
  color: #8c8c8c;
  line-height: 1.5;
  display: block;
}

/* 按钮容器 */
.button-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx 40rpx 30rpx 40rpx;
  display: flex;
  flex-direction: row;
  gap: 24rpx;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
}

/* 操作按钮（关闭/开启） */
.btn-action-wrapper {
  flex: 1;
  height: 92rpx;
  border-radius: 12rpx;
  background-color: #ffffff;
  border: 2rpx solid #00bdb4;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.btn-action-words {
  color: #00bdb4;
  font-size: 36rpx;
  font-weight: 500;
}

/* 发布按钮 */
.btn-next-wrapper {
  flex: 1;
  height: 92rpx;
  border-radius: 12rpx;
  background-color: #00bdb4;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

/* 单个按钮时的样式 */
.button-wrapper .btn-next-wrapper:only-child {
  width: 100%;
  flex: none;
}

.btn-next-wrapper.btn-disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.btn-next-words {
  color: #ffffff;
  font-size: 36rpx;
  font-weight: 500;
}

.btn-disabled .btn-next-words {
  color: #999999;
}
</style>